from typing import Optional
from asyncio import Queue
import os

# 在模块加载时读取UA模式，避免每次函数调用都读取文件
MALICIOUS_UA_PATTERNS = set()
UA_FILE_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'docs', 'ua.txt')

try:
    with open(UA_FILE_PATH, 'r', encoding='utf-8') as f:
        for line in f:
            pattern = line.strip()
            if pattern:
                MALICIOUS_UA_PATTERNS.add(pattern.lower())
    print(f"[UA Analyzer] 成功加载 {len(MALICIOUS_UA_PATTERNS)} 个恶意UA模式。")
except FileNotFoundError:
    print(f"[UA Analyzer] 警告: 未找到UA模式文件: {UA_FILE_PATH}。UA检测功能可能受限。")
except Exception as e:
    print(f"[UA Analyzer] 警告: 加载UA模式文件时发生错误: {e}。UA检测功能可能受限。")

async def _send_status(status_queue: Optional[Queue], tool_name: str, message_type: str, data: dict):
    """辅助函数：向状态队列发送消息。"""
    if status_queue:
        await status_queue.put({
            "type": message_type,
            "step": tool_name,
            "data": data
        })

async def analyze_user_agent(user_agent_string: str, status_queue: Optional[Queue] = None) -> dict:
    """
    分析User-Agent字符串，识别已知的恶意或异常UA。
    """
    tool_name = "Internal_UA_Analyzer"
    await _send_status(status_queue, tool_name, "tool_start", {"user_agent": user_agent_string})

    analysis_result = {
        "is_malicious": False,
        "is_suspicious": False,
        "reason": "看起来是正常的浏览器UA"
    }

    if not user_agent_string:
        analysis_result["reason"] = "User-Agent字符串为空。"
        await _send_status(status_queue, tool_name, "tool_end", {"user_agent": user_agent_string, "result": analysis_result})
        return {"source": "Internal-UA-Analyzer", "data": analysis_result, "status": "success"}

    ua_lower = user_agent_string.lower()

    for pattern in MALICIOUS_UA_PATTERNS:
        if pattern in ua_lower:
            analysis_result = {
                "is_malicious": True,
                "is_suspicious": True,
                "reason": f"User-Agent包含已知恶意模式: '{pattern}'"
            }
            break

    await _send_status(status_queue, tool_name, "tool_end", {"user_agent": user_agent_string, "result": analysis_result})
    return {"source": "Internal-UA-Analyzer", "data": analysis_result, "status": "success"}